package com.atguigu.juc;


import java.sql.Time;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class MyResource{
    private volatile boolean FLAG = true; //默认开启，进行生产 + 消费
    private AtomicInteger atomicInteger = new AtomicInteger();

    BlockingQueue<String> blockingQueue = null;

    public MyResource(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    public void myProd() throws Exception{
        String data = null;
        Boolean returnVal ;
        while (FLAG) {
            data = atomicInteger.incrementAndGet()+"";
            returnVal = blockingQueue.offer(data,2L, TimeUnit.SECONDS);
            if (returnVal){
                System.out.println(Thread.currentThread().getName()+ "\t生产队列" + data + "成功！");
            }else{
                System.out.println(Thread.currentThread().getName()+ "\t生产队列" + data + "失败！");
     }
            TimeUnit.SECONDS.sleep(1);
        }
        System.out.println(Thread.currentThread().getName()+ "表示FLAG等于false 停止生产");
    }

    public void myConsumer() throws Exception{
        String result = null;
        while (FLAG){
            result = blockingQueue.poll(2,TimeUnit.SECONDS);
            if (result == null || result.equalsIgnoreCase("")) {
                System.out.println(Thread.currentThread().getName()+ "超过两秒未取到消息 退出" );
            }
            System.out.println(Thread.currentThread().getName()+ "消费队列" + result + "消费成功" );
        }
    }

    public void stop () {
        this.FLAG = false;
    }
}

public class ProdConsumer_BlockQueueDemo {

    public static void main(String[] args)  throws Exception{
        MyResource myResource = new MyResource(new ArrayBlockingQueue<>(10));

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName()+ "生产线程启动");
            try {
                myResource.myProd();
            } catch (Exception e) {
                e.printStackTrace();
            }
        },"Prod").start();

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName()+ "消费线程启动");
            try {
                myResource.myConsumer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        },"Consumer").start();


        TimeUnit.SECONDS.sleep(10);
        System.out.println("结束生产");
        myResource.stop();
    }
}
